package com.rihel.dao;

import com.rihel.model.Goods;
import com.rihel.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class GoodsDao {
    public ArrayList<Goods> getAllGoods(){
        Connection conn=null;
        PreparedStatement pstt = null;
        ResultSet rs = null;
        ArrayList<Goods> goodsList = new ArrayList<Goods>();
        try {
            conn = DBUtil.getconn();
            pstt=conn.prepareStatement("SELECT * FROM goods");
            rs=pstt.executeQuery();
            while (rs.next()){
                goodsList.add(generatorGoodsForResultSet(rs));
            }
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
            return goodsList;
        }finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public Goods getGoodsById(Integer id){
        try {
            return getGoods("id",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    private Goods getGoods(String str,Object value) throws SQLException {
        Connection conn = DBUtil.getconn();
        Goods goods = null;
        PreparedStatement psm = conn.prepareStatement("SELECT * FROM goods WHERE "+str+"=?");
        if(value instanceof Integer){
            psm.setInt(1, (Integer) value);
        }else if(value instanceof String){
            psm.setString(1, (String) value);
        }
        ResultSet rs = psm.executeQuery();
        if(rs.next()){
            goods=generatorGoodsForResultSet(rs);
        }
        return goods;
    }
    private Goods generatorGoodsForResultSet(ResultSet rs) throws SQLException {
        Goods goods =new Goods();
        goods.setId(rs.getInt("id"));
        goods.setName(rs.getString("name"));
        goods.setNumber(rs.getInt("number"));
        goods.setPicUrl(rs.getString("pic_url"));
        goods.setPrice(rs.getInt("price"));
        return goods;
    }
}
